package com.itrip.log.test;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.itrip.log.util.Util;


/**
 * Function:XXX TODO add desc
 *
 * @date:2016年11月21日/下午10:17:16
 * @Author:coder_czp@126.com
 * @version:1.0
 */
public class Lexer {

	interface IMethod {
		Object invoke(Object arg);

		IMethod trim = new IMethod() {
			@Override
			public Object invoke(Object arg) {
				return arg.toString().trim();
			}
		};
		IMethod upper = new IMethod() {
			@Override
			public Object invoke(Object arg) {
				return arg.toString().toUpperCase();
			}
		};
		IMethod low = new IMethod() {
			@Override
			public Object invoke(Object arg) {
				return arg.toString().toLowerCase();
			}
		};
	}

	private static Map<String, IMethod> registMethod = new HashMap<String, IMethod>();
	private static Pattern methodPattern = Pattern.compile("\\s*((\\w+?)\\(\\w+?\\))");
	private static Pattern argPattern = Pattern.compile("\\(((\\s*\\w+\\s*,?\\s*)+)\\)");

	static {
		registMethod.put("trim", IMethod.trim);
		registMethod.put("low", IMethod.low);
		registMethod.put("upper", IMethod.upper);
	}

	public static void main(String[] args) {
		System.out.println(Util.decrypt("0k3z/HhZGwUamWgLMUcNrA=="));
		String text = "low(upper(trim(test_cf,yyd,1212ga,oohh),vg))";
		LinkedList<String> stack = parseStack(text);
		while (!stack.isEmpty()) {
			String remove = stack.remove();
			System.out.println(remove);
//			IMethod method = registMethod.get(remove);
//			if (method == null)
//				throw new IllegalArgumentException("unknow function:" + remove);
//			arg = method.invoke(arg);
		}
	}

	private static LinkedList<String> parseStack(String text) {
		Matcher matchArg = argPattern.matcher(text);
		if (!matchArg.find())
			throw new IllegalArgumentException("param is empty");
		LinkedList<String> stack = new LinkedList<String>();
		String group = matchArg.group(1);
		String[] param = group.split(",");
		for (String string : param) {
			stack.add(string);
		}
		String replace = text.replace(group, "0");
		Matcher matchMethod = methodPattern.matcher(replace);
		int i = 1;
		while (matchMethod.find()) {
			stack.add(matchMethod.group(1));
			matchMethod = methodPattern.matcher(matchMethod.replaceFirst(String.valueOf(i++)));
		}
		return stack;
	}
}
